<template lang="pug">
.campaign(v-loading.fullscreen.lock="loading")
  title-header(style="margin-left: 43px;") 基本信息
  .campaign-basic-info
    el-form(
      label-position="right",
      label-width="110px",
      :model="campaign",
    )
      el-form-item(label="URL")
        el-input(
          autosize,
          type="textarea",
          v-model="campaign.url",
        )
      el-form-item(label="目标价格")
        el-input(
          autosize,
          v-model="campaign.target_price",
        )
  form-button-grounp(
    @confirm="onConfirm",
    @cancel="$router.go(-1)",
  )
</template>

<script>
import axios from "axios"
import TitleHeader from "title-header"
import SubTitleHeader from "sub-title-header"
import pickBy from "lodash/pickBy"
import { format4backend, FormValidator } from "utils"
import compareAsc from "date-fns/compare_asc"
import FormButtonGrounp from "form-button-grounp"

export default {
  components: {
    TitleHeader,
    SubTitleHeader,
    FormButtonGrounp,
  },
  data() {
    return {
      campaign: {
        url: "", // 类型默认品牌形象
        target_price: null,
      },
      campaignID: this.$route.params.id,
      isEdit: this.$route.params.id != null,
      loading: false,
    }
  },
  mounted() {
    if(this.isEdit) this.initEditMode()
  },
  methods: {
    onConfirm() {
      if(!this.validate()) return
      const params = {
        url: this.campaign.url,
        target_price: this.campaign.target_price,
      }
      const url = this.isEdit
        ? "/business/campaign/pc/update"
        : "/spiders"
      const msg = this.isEdit ? "编辑成功" : "新建成功"
      this.loading = true
      axios
        .post(url, params)
        .then(res => {
          this.loading = false
          this.$message.success(msg)
          this.$router.go(-1)
        })
        .catch(e => {
          this.loading = false
        })
    },
    validate() {
      const validator = new FormValidator()
      validator.add(this.campaign.url, "isEmpty", "请填URL")
      validator.add(
        this.campaign.target_price,
        "isEmpty",
        "请填写目标价格",
      )

      const errorMsg = validator.validate()
      if(errorMsg) {
        this.$message.error(errorMsg)
        return false
      }
      return true
    },
    initEditMode() {
      this.loading = true
      axios
        .get("/business/campaign/pc/getCampaignInfo", {
          params: { campaign_id: this.campaignID },
        })
        .then(res => {
          this.mediums = res.data.spotplan_list
          this.campaign = res.data
          this.$store.commit("UPDATE_START_DATE", res.data.start_date)
          this.$store.commit("UPDATE_END_DATE", res.data.end_date)
          this.loading = false
        })
        .catch(_ => {
          this.loading = false
        })
    },
  },
}
</script>

<style lang="stylus">
.campaign-basic-info
  margin-top: 25px
  width: 400px

.campaign-basic-info__form__require
  color: red
  margin-right: 5px
</style>